package pw.hsu.messagerelayer.utils;


import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 发送请求
 *
 * @author hosea
 */
public class UrlRelayerManager {

    public static final int CODE_SUCCESS = 0x1;
    public static final int CODE_FAILE = 0x0;

    /**
     * 发送短信至目标邮件
     *
     * @param dataManager
     * @param content
     * @param mobile
     * @return
     */
    public static int relayUrl(SharedPreferenceUtil dataManager, String prefix, String suffix, String content, String mobile) {

        String url = dataManager.getUrlHost();
        String postBody = dataManager.getUrlTemplate();
        if (content == null || content == "") {
            url = url
                    .replace("{{time}}", getNowDateTime())
                    .replace("{{prefix}}", getNowDateTime())
                    .replace("{{suffix}}", getNowDateTime())
                    .replace("{{phone}}", mobile)
                    .replace("{{msg}}", content);
        } else {
            postBody = postBody
                    .replace("{{time}}", getNowDateTime())
                    .replace("{{prefix}}", getNowDateTime())
                    .replace("{{suffix}}", getNowDateTime())
                    .replace("{{phone}}", mobile)
                    .replace("{{msg}}", content);
        }

        Log.d("debug", "relayUrl postBody: " + postBody);
        String rs = submitPostData(url, postBody);
        Log.d("debug", "relayUrl: " + rs);
//        dataManager.setUrlLogContent("---------------------------------------\n" + postBody +"\n"+ rs);
        return CODE_SUCCESS;
//            return CODE_FAILE;
//            return CODE_FAILE;

    }

    /**
     * 获取当前时间字符串
     *
     * @return string 时间
     */
    private static String getNowDateTime() {
        String strFormat = "yyyy-MM-dd HH:mm:ss";
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat(strFormat);
        return df.format(now);
    }


    /**
     * 提交post请求
     *
     * @param strUrlPath 链接
     * @param params     参数
     * @return 错误码
     */
    public static String submitPostData(String strUrlPath, String params) {
        //获得请求体
        byte[] data = params.getBytes();
        try {

            //String urlPath = "http://192.168.1.9:80/JJKSms/RecSms.php";
            URL url = new URL(strUrlPath);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            //打开输入流，以便从服务器获取数据
            httpURLConnection.setDoInput(true);
            //打开输出流，以便向服务器提交数据
            httpURLConnection.setDoOutput(true);
            //设置以Post方式提交数据
            httpURLConnection.setRequestMethod("POST");
            //使用Post方式不能使用缓存
            httpURLConnection.setUseCaches(false);
            //设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //设置请求体的长度
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获得输出流，向服务器写入数据
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            //获得服务器的响应码
            int response = httpURLConnection.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                //处理服务器的响应结果
                return dealResponseResult(inptStream);
            }
        } catch (IOException e) {
            //e.printStackTrace();
            return "err: " + e.getMessage().toString();
        }
        return "-1";
    }

    public static String dealResponseResult(InputStream inputStream) {
        //存储处理结果
        String resultData = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }


}
